package nero.yncc.com.createart.activity;

import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import nero.yncc.com.createart.R;
import nero.yncc.com.createart.adapter.AdapterIndexHotSale;
import nero.yncc.com.createart.adapter.AdapterSearchAll;
import nero.yncc.com.createart.base.BaseActivity;
import nero.yncc.com.createart.base.Constants;
import nero.yncc.com.createart.bean.BeanAttr;
import nero.yncc.com.createart.bean.BeanCategory;
import nero.yncc.com.createart.bean.BeanSearchAll;
import nero.yncc.com.createart.bean.BeanType;
import nero.yncc.com.createart.bean.BeanTypeIn;
import nero.yncc.com.createart.bean.GodBean;
import nero.yncc.com.createart.bean.GoodsAllBean;
import nero.yncc.com.createart.bean.SearchInBean;
import nero.yncc.com.createart.custom.IconView;
import nero.yncc.com.createart.custom.MyRecyclerView;
import nero.yncc.com.createart.utils.ArrayUtils;
import nero.yncc.com.createart.utils.HttpUtils;
import nero.yncc.com.createart.utils.PopGuige;
import nero.yncc.com.createart.utils.ShopCarUtil;
import nero.yncc.com.createart.utils.TextUtil;
import nero.yncc.com.createart.utils.ToastUtil;

/**
 * Created by nero on 17-6-26.
 */
@ContentView(R.layout.activity_search_allgod)
public class ActivitySearchAllGod extends BaseActivity {
    //排序大布局ActivitySearchAllGod
    @ViewInject(R.id.rl_zonghe)
    RelativeLayout rl_zonghe;
    @ViewInject(R.id.rl_salenum)
    RelativeLayout rl_salenum;
    @ViewInject(R.id.rl_price)
    RelativeLayout rl_price;
    @ViewInject(R.id.rl_search_choose)
    RelativeLayout rl_search_choose;

    @ViewInject(R.id.et_search)
    EditText et_search;  //搜索textview

    @ViewInject(R.id.rc_list)
    public PullToRefreshListView pl_good;

    @ViewInject(R.id.icon_back)
    IconView icon_back;

    @ViewInject(R.id.tv_zonghe)
    TextView tv_zonghe;
    @ViewInject(R.id.tv_salenum)
    TextView tv_salenum;
    @ViewInject(R.id.tv_price)
    TextView tv_price;
    @ViewInject(R.id.tv_search_choose)
    TextView tv_search_choose;

    @ViewInject(R.id.icon_salenum_up)
    IconView icon_salenum_up;
    @ViewInject(R.id.icon_salenum_down)
    IconView icon_salenum_down;
    @ViewInject(R.id.icon_price_up)
    IconView icon_price_up;
    @ViewInject(R.id.icon_price_down)
    IconView icon_price_down;
    @ViewInject(R.id.iconNodata)
    IconView iconNodata;
    @ViewInject(R.id.tv_shopcar_num)
    TextView tv_shopcar_num;

    ArrayList<GodBean.Goods> arrayList_good;
    AdapterIndexHotSale adapter_good;

    int saleNumSort = 0;//0上1下
    int priceSort = 0;//0上1下


    //下面是pop搜索界面～～长啊。。
    PopupWindow popupWindow_search;

    GestureDetector gestureDetector;
    View view_pop_search;
    TextView tv_type_pop;

    LinearLayout ll_pop_root;
    AdapterSearchAll adapterSearchAll;
    ArrayList<BeanAttr> arrayList_search;
    MyRecyclerView rc_list_pop;

    TextView btn_search;//搜索
    EditText et_start, et_end;//pop上面的价格区间

    boolean canClosePop = false;//是否能关闭pop


    private static int RESULT_ALL_TYPE = 1;
    Timer timer_search;//搜索timer
    //所有分类的数组
    public static ArrayList<BeanCategory> arrayList_type;

    @Override
    protected void initView() {
        super.initView();
        icon_salenum_up.setTextColor(getResources().getColor(R.color.project_yellow));
        icon_price_up.setTextColor(getResources().getColor(R.color.project_yellow));
        initPop();
        initPopType();

        setPullToRefreshListView(pl_good);
    }

    private void initPop() {

        view_pop_search = LinearLayout.inflate(mContext, R.layout.pop_search_allgod, null);
        tv_type_pop = view_pop_search.findViewById(R.id.tv_type_pop);
        rc_list_pop = view_pop_search.findViewById(R.id.rc_list_pop);
        ll_pop_root = view_pop_search.findViewById(R.id.ll_pop_root);
        btn_search = view_pop_search.findViewById(R.id.btn_search);
        et_start = view_pop_search.findViewById(R.id.et_start);
        et_end = view_pop_search.findViewById(R.id.et_end);

        popupWindow_search = new PopupWindow(view_pop_search, -1, -1);
        arrayList_search = new ArrayList<>();

        LinearLayout ll_allType = view_pop_search.findViewById(R.id.ll_allType);
        ll_allType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, ActivitySearchAllType.class);
                intent.putExtra("array", arrayList_type);
                startActivityForResult(intent, RESULT_ALL_TYPE);
            }
        });

        adapterSearchAll = new AdapterSearchAll(mContext, arrayList_search, this);
        rc_list_pop.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        rc_list_pop.setAdapter(adapterSearchAll);
        TextView tv_reset = view_pop_search.findViewById(R.id.tv_reset);
        tv_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapterSearchAll.reset();
                adapterSearchAll.notifyDataSetChanged();
                href = "";
                keyword = "";
                typeId = "";
                pl_good.setPullMode(PullToRefreshBase.Mode.PULL_FROM_START);
                pl_good.isPullToRefreshEnabled();
                popupWindow_search.dismiss();
                et_search.clearFocus();
            }
        });

        popupWindow_search.setFocusable(true);
        popupWindow_search.setBackgroundDrawable(new ColorDrawable(0));
    }

    private void initPopType() {
        //pop搜索界面
        arrayList_type = new ArrayList<>();
    }

    /**
     * 返回来的是选中的数据 展示再pop中
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_ALL_TYPE && resultCode == 200) {
            try{
                BeanCategory bean = (BeanCategory) data.getSerializableExtra("data");
                tv_type_pop.setText(bean.getName());
                typeId = bean.getId();
                pl_good.setRefreshing(true);
            }catch (Exception e){
                tv_type_pop.setText("全部");
                typeId = "0";
                pl_good.setRefreshing(true);
            }finally {
                popupWindow_search.dismiss();
                closeSoftware();
                et_search.clearFocus();
            }

        }

    }

    @Override
    protected void initData() {
        super.initData();
        arrayList_good = new ArrayList<>();
        adapter_good = new AdapterIndexHotSale(mContext, arrayList_good);
        pl_good.setAdapter(adapter_good);

        gestureDetector = new GestureDetector(this, onGestureListener);

        String key = getIntent().getStringExtra("keyword");
        if (!TextUtils.isEmpty(key)) {
            keyword = key;
            et_search.setText(key);
            et_search.setSelection(key.length());
        }
        getCategory("0");

        typeId = getIntent().getStringExtra("type");
        if (typeId == null || keyword.equals("null"))
            typeId="0";


    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    protected void initListener() {
        super.initListener();
        pl_good.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(mContext, ActivityGoodDetail.class);
                intent.putExtra("id", arrayList_good.get((int) l).getGoods_id());
                startActivity(intent);
            }
        });
        rl_zonghe.setOnClickListener(this);
        rl_salenum.setOnClickListener(this);
        rl_price.setOnClickListener(this);
        rl_search_choose.setOnClickListener(this);

        icon_back.setOnClickListener(this);

        view_pop_search.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return gestureDetector.onTouchEvent(motionEvent);

            }
        });

        pl_good.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                page = 1;
                arrayList_good.clear();
                adapter_good.notifyDataSetChanged();
                getData();
                canLoad = true;
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page += 1;
                getData();
            }
        });
        pl_good.setRefreshing(true);
        changeColor(CHOOSE_ZONGGE); //默认选中综合

        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = et_search.getText().toString();
                    pl_good.setRefreshing(true);
                    return true;
                }
                return false;
            }
        });

        et_search.clearFocus();
        et_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) {
                    keyword = et_search.getText().toString();
                    pl_good.setRefreshing(true);
                }
            }
        });

        btn_search.setOnClickListener(this);
        ll_pop_root.setOnClickListener(this);
        et_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (timer_search != null)
                    timer_search.cancel();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                timer_search = new Timer();
                timer_search.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                keyword = et_search.getText().toString();
                                pl_good.setRefreshing(true);
                            }
                        });

                    }
                }, 1000);
            }
        });
        tv_shopcar_num.setOnClickListener(this);
    }


    boolean canLoad = true;

    @Override
    protected void doClick(int id) {
        super.doClick(id);

        switch (id) {
            case R.id.rl_zonghe:
                changeColor(CHOOSE_ZONGGE);

                break;
            case R.id.rl_salenum:
                changeColor(CHOOSE_SALENUM);
                break;
            case R.id.rl_price:
                changeColor(CHOOSE_PRICE);
                break;
            case R.id.rl_search_choose:

                popupWindow_search.setAnimationStyle(R.style.popAinmation);
                popupWindow_search.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                //播放背景渐变动画
                ValueAnimator animator_back = ValueAnimator.ofInt(0, 150);
                animator_back.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    @Override
                    public void onAnimationUpdate(ValueAnimator valueAnimator) {
                        int nowValue = (int) valueAnimator.getAnimatedValue();
                        if (nowValue < 30) {
                            return;
                        }
                        ll_pop_root.setBackgroundColor(Color.argb(nowValue - 30, 0, 0, 0));
                        if (nowValue == 149)
                            canClosePop = true;
                    }
                });
                animator_back.setDuration(1500).start();
                break;
            case R.id.icon_back:
                finish();
                break;
            case R.id.btn_search:
                //获取价格区间
                String start = et_start.getText().toString();
                String end = et_end.getText().toString();
                if (TextUtils.isEmpty(start) || TextUtils.isEmpty(end)) {
                    showToast("请输入开始金额和结束金额");
                    return;
                }
                href = Constants.IMAGE_HOST + "/index.php/Api/Goods/goodsList/id/0/price/" + start + "-" + end + "";
                pl_good.setRefreshing(true);
                popupWindow_search.dismiss();
                et_search.clearFocus();
//
                break;
            case R.id.ll_pop_root:
                popupWindow_search.dismiss();
                break;
            case R.id.tv_shopcar_num:
                startActivity(new Intent(mContext, ActivityShopcar.class));
                break;
        }
    }

    private static final int CHOOSE_ZONGGE = 1, CHOOSE_SALENUM = 2, CHOOSE_PRICE = 3, CHOOSE_SEARCH = 4;

    /**
     * 改变排序条件的颜色和排序条件
     */
    private void changeColor(int chooseId) {
        tv_zonghe.setTextColor(getResources().getColor(R.color.textColorGray));
        tv_salenum.setTextColor(getResources().getColor(R.color.textColorGray));
        tv_price.setTextColor(getResources().getColor(R.color.textColorGray));
        tv_search_choose.setTextColor(getResources().getColor(R.color.textColorGray));

        switch (chooseId) {
            case CHOOSE_ZONGGE:
                tv_zonghe.setTextColor(getResources().getColor(R.color.project_yellow));
                sort = "click_count";
                pl_good.setRefreshing(true);
                break;
            case CHOOSE_SALENUM:
                tv_salenum.setTextColor(getResources().getColor(R.color.project_yellow));
                sort = "sales_sum";
                if (saleNumSort == 0) {
                    saleNumSort = 1;
                    icon_salenum_up.setTextColor(getResources().getColor(R.color.textColorGray));
                    icon_salenum_down.setTextColor(getResources().getColor(R.color.project_yellow));
                    sort_asc = "desc";
                } else {
                    saleNumSort = 0;
                    icon_salenum_up.setTextColor(getResources().getColor(R.color.project_yellow));
                    icon_salenum_down.setTextColor(getResources().getColor(R.color.textColorGray));
                    sort_asc = "asc";
                }
                pl_good.setRefreshing(true);
                break;
            case CHOOSE_PRICE:
                tv_price.setTextColor(getResources().getColor(R.color.project_yellow));
                sort = "shop_price";
                if (priceSort == 0) {
                    priceSort = 1;
                    icon_price_up.setTextColor(getResources().getColor(R.color.textColorGray));
                    icon_price_down.setTextColor(getResources().getColor(R.color.project_yellow));
                    sort_asc = "desc";
                } else {
                    priceSort = 0;
                    icon_price_up.setTextColor(getResources().getColor(R.color.project_yellow));
                    icon_price_down.setTextColor(getResources().getColor(R.color.textColorGray));
                    sort_asc = "asc";
                }
                pl_good.setRefreshing(true);
                break;
            case CHOOSE_SEARCH:
                tv_search_choose.setTextColor(getResources().getColor(R.color.project_yellow));
                break;

        }

    }

    String keyword = "";//关键字啦
    String sort = "click_count";//排序的类型：综合:click_count销量:sales_sum价格:shop_price新品:goods_id
    String typeId = "0";//当前产品分类S
    String sort_asc = "asc";//升序:asc降序:desc
    int page = 1;
    int pageSize = 10;


    public String href = "";

    @Override
    protected void getData() {
        super.getData();
        closeSoftware();
        et_search.clearFocus();
        HashMap<String, String> hashMap = new HashMap();
        if (href == "") {
            hashMap.put("id", typeId);
            hashMap.put("sort", sort);

            hashMap.put("keyword", keyword);
            hashMap.put("sort_asc", sort_asc);
            hashMap.put("user_id", userBean.getUser_id());
            hashMap.put("p", page + "");
            href = Constants.API_GOODLIST;
        } else {
            popupWindow_search.dismiss();
        }
        HttpUtils.get(this, href, hashMap, GoodsAllBean.class, HttpUtils.TYPE_OBJECT, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                GoodsAllBean bean = (GoodsAllBean) json;
                if (!canLoad) {
                    pl_good.onRefreshComplete();

                    showToast("没有更多内容啦");
                    return;
                }

                if (bean.getGoods_list().size() < pageSize) {
                    canLoad = false;
                }
                ArrayUtils.copy(bean.getGoods_list(), arrayList_good, false);
                ArrayUtils.copy(bean.getFilter_spec(), arrayList_search, true);
                ArrayUtils.copy(bean.getFilter_attr(), arrayList_search, false);
                adapter_good.notifyDataSetChanged();
                adapterSearchAll.notifyDataSetChanged();
                pl_good.onRefreshComplete();
                href = "";
                if (arrayList_good.size() <= 0) {
                    iconNodata.setVisibility(View.VISIBLE);
                    pl_good.setVisibility(View.GONE);
                } else {
                    iconNodata.setVisibility(View.GONE);
                    pl_good.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void fail(String failMsg) {
                showToast("获取商品列表失败，请检查网络");
                pl_good.onRefreshComplete();
                href = "";
            }
        });

        ShopCarUtil.getShopCarNum(this, userBean, new ShopCarUtil.ShopCarGetListener() {
            @Override
            public void success(String num) {
                tv_shopcar_num.setText(num);
            }

            @Override
            public void fail(String num) {

            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            if (popupWindow_search.isShowing()) {
                if (canClosePop) {
                    ll_pop_root.setBackgroundColor(Color.argb(0, 0, 0, 0));
                    popupWindow_search.dismiss();
                    canClosePop = false;
                }
                return true;
            }

        }
        return super.onKeyDown(keyCode, event);
    }


    public void getCategory(String categoryId) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("category_id", categoryId);
        HttpUtils.get(this, Constants.API_CATEGORY, hashMap, null, HttpUtils.TYPE_NOTHING, new HttpUtils.HttpCallback() {
            @Override
            public void success(String msg, Object json) {
                try {
                    JSONArray jsonArray = new JSONObject(json.toString()).getJSONArray("list");
                    for (int a = 0; a < jsonArray.length(); a++) {
                        BeanCategory beanCategory = JSON.parseObject(jsonArray.getString(a), BeanCategory.class);
                        arrayList_type.add(beanCategory);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void fail(String failMsg) {

            }
        });
    }

    private GestureDetector.OnGestureListener onGestureListener =
            new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                       float velocityY) {
                    if (e1 == null || e2 == null || !popupWindow_search.isShowing())
                        return false;
                    float x = e2.getX() - e1.getX();
                    float y = e2.getY() - e1.getY();

                    if (x > 0) {

                        if (popupWindow_search.isShowing() && canClosePop) {
                            ll_pop_root.setBackgroundColor(Color.argb(0, 0, 0, 0));
                            popupWindow_search.dismiss();
                            canClosePop = false;

                        }
                    }
                    return true;
                }
            };


}
